import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { 
  ScheduleResponse, 
  ScheduleCreate, 
  ScheduleUpdate
} from '@/api/models'
import { getSchedules } from '@/api/schedules/schedules'

export const useScheduleStore = defineStore('schedule', () => {
  // 状态
  const schedules = ref<ScheduleResponse[]>([])
  const todaySchedules = ref<ScheduleResponse[]>([])
  const weekSchedules = ref<ScheduleResponse[]>([])
  const monthSchedules = ref<ScheduleResponse[]>([])
  const loading = ref(false)
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)
  
  // 统计数据
  const stats = ref({
    total: 0,
    completed: 0,
    pending: 0,
    inProgress: 0,
    cancelled: 0,
    todayCount: 0,
    weekCount: 0,
    monthCount: 0
  })

  // 计算属性
  const scheduleById = computed(() => {
    return (id: number) => schedules.value.find(item => item.id === id)
  })

  const schedulesByStatus = computed(() => {
    return (status: ScheduleResponse['status']) => {
      return schedules.value.filter(item => item.status === status)
    }
  })

  const schedulesByPriority = computed(() => {
    return (priority: ScheduleResponse['priority']) => {
      return schedules.value.filter(item => item.priority === priority)
    }
  })

  const upcomingSchedules = computed(() => {
    const now = new Date()
    return schedules.value
      .filter(item => new Date(item.start_time) > now)
      .sort((a, b) => new Date(a.start_time).getTime() - new Date(b.start_time).getTime())
      .slice(0, 5)
  })

  // 方法
  const setLoading = (value: boolean) => {
    loading.value = value
  }

  const setSchedules = (data: ScheduleResponse[]) => {
    schedules.value = data
  }

  const setTodaySchedules = (data: ScheduleResponse[]) => {
    todaySchedules.value = data
  }

  const setWeekSchedules = (data: ScheduleResponse[]) => {
    weekSchedules.value = data
  }

  const setMonthSchedules = (data: ScheduleResponse[]) => {
    monthSchedules.value = data
  }

  const setStats = (data: any) => {
    stats.value = { ...stats.value, ...data }
  }

  const setPagination = (page: number, totalItems: number) => {
    currentPage.value = page
    total.value = totalItems
  }

  // 获取日程列表
  const fetchScheduleList = async (params?: any) => {
    try {
      setLoading(true)
      const { getSchedulesEndpointApiV1SchedulesGet } = getSchedules()
      const response = await getSchedulesEndpointApiV1SchedulesGet({
        page: currentPage.value,
        page_size: pageSize.value,
        ...params
      })
      
      setSchedules(response.schedules)
      setPagination(response.page || 1, response.total)
      return response
    } catch (error) {
      console.error('获取日程列表失败:', error)
      throw error
    } finally {
      setLoading(false)
    }
  }

  // 获取单个日程详情
  const fetchScheduleDetail = async (id: number) => {
    try {
      setLoading(true)
      const { getScheduleEndpointApiV1SchedulesScheduleIdGet } = getSchedules()
      const response = await getScheduleEndpointApiV1SchedulesScheduleIdGet(id)
      return response
    } catch (error) {
      console.error('获取日程详情失败:', error)
      throw error
    } finally {
      setLoading(false)
    }
  }

  // 创建日程
  const createNewSchedule = async (data: ScheduleCreate) => {
    try {
      setLoading(true)
      const { createScheduleEndpointApiV1SchedulesPost } = getSchedules()
      const response = await createScheduleEndpointApiV1SchedulesPost(data)
      
      // 添加到列表
      schedules.value.unshift(response)
      
      // 更新统计数据
      await fetchScheduleStats()
      
      ElMessage.success('日程创建成功')
      return response
    } catch (error) {
      console.error('创建日程失败:', error)
      throw error
    } finally {
      setLoading(false)
    }
  }

  // 更新日程
  const updateExistingSchedule = async (id: number, data: ScheduleUpdate) => {
    try {
      setLoading(true)
      const { updateScheduleEndpointApiV1SchedulesScheduleIdPut } = getSchedules()
      const response = await updateScheduleEndpointApiV1SchedulesScheduleIdPut(id, data)
      
      // 更新列表中的日程
      const index = schedules.value.findIndex(item => item.id === id)
      if (index !== -1) {
        schedules.value[index] = response
      }
      
      ElMessage.success('日程更新成功')
      return response
    } catch (error) {
      console.error('更新日程失败:', error)
      throw error
    } finally {
      setLoading(false)
    }
  }

  // 删除日程
  const deleteExistingSchedule = async (id: number) => {
    try {
      setLoading(true)
      const { deleteScheduleEndpointApiV1SchedulesScheduleIdDelete } = getSchedules()
      await deleteScheduleEndpointApiV1SchedulesScheduleIdDelete(id)
      
      // 从列表中移除
      schedules.value = schedules.value.filter(item => item.id !== id)
      
      // 更新统计数据
      await fetchScheduleStats()
      
      ElMessage.success('日程删除成功')
    } catch (error) {
      console.error('删除日程失败:', error)
      throw error
    } finally {
      setLoading(false)
    }
  }

  // 更新日程状态
  const updateScheduleItemStatus = async (id: number, status: ScheduleResponse['status']) => {
    try {
      setLoading(true)
      const { updateScheduleEndpointApiV1SchedulesScheduleIdPut } = getSchedules()
      const response = await updateScheduleEndpointApiV1SchedulesScheduleIdPut(id, { status })
      
      // 更新列表中的日程
      const index = schedules.value.findIndex(item => item.id === id)
      if (index !== -1) {
        schedules.value[index] = response
      }
      
      // 更新统计数据
      await fetchScheduleStats()
      
      ElMessage.success('状态更新成功')
      return response
    } catch (error) {
      console.error('更新日程状态失败:', error)
      throw error
    } finally {
      setLoading(false)
    }
  }

  // 获取日程统计
  const fetchScheduleStats = async () => {
    try {
      const { getScheduleStatsEndpointApiV1SchedulesStatsGet } = getSchedules()
      const response = await getScheduleStatsEndpointApiV1SchedulesStatsGet()
      
      // 转换统计数据格式
      const newStats = {
        total: response.total_count,
        completed: response.completed_count,
        pending: response.pending_count,
        inProgress: response.in_progress_count,
        cancelled: response.cancelled_count,
        todayCount: 0,
        weekCount: 0,
        monthCount: 0,
        highPriorityCount: response.high_priority_count,
        urgentCount: response.urgent_count
      }
      
      setStats(newStats)
      return newStats
    } catch (error) {
      console.error('获取日程统计失败:', error)
      throw error
    }
  }

  // 获取今日日程
  const fetchTodaySchedules = async () => {
    try {
      const { getSchedulesByDateRangeEndpointApiV1SchedulesByDateRangeGet } = getSchedules()
      const today = new Date()
      const tomorrow = new Date(today)
      tomorrow.setDate(tomorrow.getDate() + 1)
      
      const response = await getSchedulesByDateRangeEndpointApiV1SchedulesByDateRangeGet({
        start_date: today.toISOString().split('T')[0],
        end_date: tomorrow.toISOString().split('T')[0]
      })
      
      setTodaySchedules(response)
      return response
    } catch (error) {
      console.error('获取今日日程失败:', error)
      throw error
    }
  }

  // 获取本周日程
  const fetchWeekSchedules = async () => {
    try {
      const { getSchedulesByDateRangeEndpointApiV1SchedulesByDateRangeGet } = getSchedules()
      const today = new Date()
      const nextWeek = new Date(today)
      nextWeek.setDate(nextWeek.getDate() + 7)
      
      const response = await getSchedulesByDateRangeEndpointApiV1SchedulesByDateRangeGet({
        start_date: today.toISOString().split('T')[0],
        end_date: nextWeek.toISOString().split('T')[0]
      })
      
      setWeekSchedules(response)
      return response
    } catch (error) {
      console.error('获取本周日程失败:', error)
      throw error
    }
  }

  // 获取本月日程
  const fetchMonthSchedules = async () => {
    try {
      const { getSchedulesByDateRangeEndpointApiV1SchedulesByDateRangeGet } = getSchedules()
      const today = new Date()
      const nextMonth = new Date(today)
      nextMonth.setMonth(nextMonth.getMonth() + 1)
      
      const response = await getSchedulesByDateRangeEndpointApiV1SchedulesByDateRangeGet({
        start_date: today.toISOString().split('T')[0],
        end_date: nextMonth.toISOString().split('T')[0]
      })
      
      setMonthSchedules(response)
      return response
    } catch (error) {
      console.error('获取本月日程失败:', error)
      throw error
    }
  }

  // 初始化数据
  const initializeData = async () => {
    try {
      await Promise.all([
        fetchScheduleStats(),
        fetchTodaySchedules(),
        fetchWeekSchedules(),
        fetchMonthSchedules()
      ])
    } catch (error) {
      console.error('初始化日程数据失败:', error)
    }
  }

  return {
    // 状态
    schedules,
    todaySchedules,
    weekSchedules,
    monthSchedules,
    loading,
    total,
    currentPage,
    pageSize,
    stats,
    
    // 计算属性
    scheduleById,
    schedulesByStatus,
    schedulesByPriority,
    upcomingSchedules,
    
    // 方法
    setLoading,
    setSchedules,
    setTodaySchedules,
    setWeekSchedules,
    setMonthSchedules,
    setStats,
    setPagination,
    fetchScheduleList,
    fetchScheduleDetail,
    createNewSchedule,
    updateExistingSchedule,
    deleteExistingSchedule,
    updateScheduleItemStatus,
    fetchScheduleStats,
    fetchTodaySchedules,
    fetchWeekSchedules,
    fetchMonthSchedules,
    initializeData
  }
})
